package com.bmw.seed.service.impl;

import com.bmw.seed.dao.UserRegistInfoDao;
import com.bmw.seed.model.UserRegistInfo;
import com.bmw.seed.service.UserRegistInfoService;
import com.bmw.seed.util.bean.PageResp;
import com.bmw.seed.util.bean.RegisReq;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Classname: UserRegistInfoServiceImpl
 * Package: com.bmw.seed.service.impl
 * Description:
 *
 * @Author 王少伟
 * @Create 2024/1/29 14:05
 * @Version 1.8
 */
@Service("userRegistInfoService")
@Slf4j
public class UserRegistInfoServiceImpl implements UserRegistInfoService {
    @Autowired
    UserRegistInfoDao userRegistInfoDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long regist(RegisReq req) {
        //悲观锁
        UserRegistInfo registInfo = userRegistInfoDao.fetchByPhoneForUpdate(req.getPhone());
        if(registInfo != null){
            //手机号已经被注册
            log.info("===[手机号已经被注册]===");
            return registInfo.getId();
        }else {
            Date date = new Date();
            log.info("now time" +  date.getTime());
            UserRegistInfo info = new UserRegistInfo();
            BeanUtils.copyProperties(req,info);
            //上面的BeansUtils是复制同名的属性，相当于下面两行注释的代码
            //info.setPhone(req.getPhone());
            //info.setPassword(req.getPassWord());
            info.setPassword(DigestUtils.md5Hex(info.getPassword()));
            info.setCreateTime(date);
            info.setUpdateTime(date);
            userRegistInfoDao.insert(info);
            return info.getId();
        }
    }

    @Override
    public Long unique(RegisReq req) {
        //unique不需要添加事务，因此性能要好
        Date date = new Date();
        UserRegistInfo userRegistInfo = new UserRegistInfo();
        BeanUtils.copyProperties(req,userRegistInfo);
        userRegistInfo.setPassword(DigestUtils.md5Hex(userRegistInfo.getPassword()));
        userRegistInfo.setUpdateTime(date);
        userRegistInfo.setCreateTime(date);
        try {
            userRegistInfoDao.insert(userRegistInfo);

        }catch (Exception e){
            if (e.getMessage().indexOf("Duplicate entry") >= 0){
                userRegistInfo = userRegistInfoDao.getByPhone(req.getPhone());
            }else {
                    log.error(e.getMessage(),e);
                    throw new RuntimeException(e.getMessage());
            }
        }
        return userRegistInfo.getId();
    }
}
